package com.ltmall.api.dao.impl;

import com.ltmall.api.bean.ClientAccount;
import com.ltmall.api.dao.IClientAccountDAO;
import org.hibernate.Query;
import org.hibernate.Session;

import java.util.Date;
import java.util.List;

import static com.ltmall.api.util.HibernateUtil.getSession;

public class ClientAccountDAO extends BaseEntityDAO<ClientAccount> implements IClientAccountDAO {

    @Override
    public ClientAccount getClientAccount(int userID) {
        List list = this.getHibernateTemplate().find("from ClientAccount ca where ca.userID = ? ",
            new Object[] { userID });
        if (list.size() > 0) {
            return (ClientAccount) list.get(0);
        }
        return null;
    }

    @Override
    public boolean updateAccountPoint(int userID, int point) {
        String hql = "update ClientAccount set point = ? where user_id = ?";
        try {
            Session session = getSession();
            Query query = session.createQuery(hql);
            query.setParameter(0, point);
            query.setParameter(1, userID);
            int number = query.executeUpdate();
            if (number == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean updateExpiration(int userID, Date expiration) {
        String hql = "update ClientAccount set privilege_expiration = ? where user_id  = ?";
        try {
            Session session = getSession();
            Query query = session.createQuery(hql);
            query.setParameter(0, expiration);
            query.setParameter(1, userID);
            int number = query.executeUpdate();
            if (number == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
